<template>
  <div class="flipNumber second" :class="{'running':running}">
    <div class="time front" :data-number="front" />
    <div class="time back" :data-number="back" />
  </div>
</template>
<script>
export default {
  name: 'FlipNumber',
  props: {
    back: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      front: 0,
      running: false,
      animateTime: 0.6
    }
  },
  watch: {
    back(val, oldVal) {
      if (val !== oldVal) {
        this.animation()
      }
    }
  },
  created() {
    this.front = this.back
  },
  methods: {
    animation() {
      this.running = true
      setTimeout(() => {
        this.running = false
        const back = this.back
        this.front = back
      }, this.animateTime * 1000)
    }
  }
}
</script>

<style lang="less" scoped>

  /**
  *翻页数字容器
   */
  .flipNumber {
    display: inline-block;
    position: relative;
    box-sizing: border-box;
    width: 40px;
    height: 60px;
    text-align: center;
    font-size: 50px;
    line-height: 60px;
    font-weight: bolder;
    background: #ffffff;
    box-shadow: 1px 1px 5px black;
    border-radius: 4px;
    overflow: hidden;
  }
  /**
  *页样式,用前后伪元素实现翻页的样式
  *前后伪元素的值为.time中data-number属性的值
  *before是上半页，after是下半页
  *伪元素一个：是css2写法,两个：：是css3写法
   */
  .time::before, .time::after {
    content: attr(data-number);
    position: absolute;
    left: 0;
    right: 0;
    overflow: hidden;
    color: #959595;
    background: #191919;
    perspective: 100px;
    -webkit-perspective: 160px;
  }

  .time::before {
    top: 0;
    bottom: 50%;
    border-bottom: 1px solid #717171; /*转轴*/
  }

  .time::after {
    top: 50%;
    bottom: 0;
    line-height: 0;
  }

  /*翻转前*/
  .flipNumber .front::after, .flipNumber .back::before {
    z-index: 1;
  }

  .flipNumber .back::after {
    z-index: 2;
    transform-origin: center top;
    -webkit-transform-origin: center top;
    transform: rotateX(0.5turn); /*转半圈*/
    -webkit-transform: rotateX(0.5turn);
  }

  .flipNumber .front::before {
    z-index: 3;
  }

  /*翻转后*/
  .flipNumber.running .front::before {
    transform-origin: center bottom;
    -webkit-transform-origin: center bottom;
    animation: frontFlipDown 0.6s ease-in-out;
    -webkit-animation: frontFlipDown 0.6s ease-in-out;
    box-shadow: 0 -2px 6px rgba(255, 255, 255, 0.3);
    backface-visibility: hidden; /*隐藏背面*/
    -webkit-backface-visibility: hidden;
  }

  .flipNumber.running .back::after {
    animation: backFlipDown 0.6s ease-in-out;
    -webkit-animation: backFlipDown 0.6s ease-in-out;
  }

  /**
  *动画
  */
  @keyframes frontFlipDown {
    to {
      transform: rotateX(0.5turn)
    }
  }

  @keyframes backFlipDown {
    to {
      transform: rotateX(0)
    }
  }

  @-webkit-keyframes frontFlipDown {
    to {
      -webkit-transform: rotateX(0.5turn);
    }
  }

  @-webkit-keyframes backFlipDown {
    to {
      -webkit-transform: rotateX(0);
    }
  }
</style>
